import type { App } from "vue";
import { successMsg, errorMsg } from "./element-plus/index"
import { t } from "@Lang/index.ts"

async function copyTextToClipboard(text:string) {
    var textArea = null;
    try {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            await navigator.clipboard.writeText(text);
            successMsg(t('text_copy_success'));
        } else {
            textArea = document.createElement("textarea");
            textArea.value = text;
            // 将textarea元素添加到DOM中
            document.body.appendChild(textArea);
            // 选择textarea中的文本
            textArea.select();
            // 执行复制命令
            var successful = document.execCommand('copy');
            if (successful) {
                successMsg(t('text_copy_success'));
            } else {
                errorMsg(t('text_copy_fail'));
            }
            // 移除textarea元素
            document.body.removeChild(textArea);
        }
    } catch (err) {
        console.error('复制文本时出现错误', err);
        if (textArea) {
            document.body.removeChild(textArea);
        }
        errorMsg(t('text_copy_fail'));
    }
}

export default (app: App) => {
    app.config.globalProperties.$copy = copyTextToClipboard;
};
